package com.qingfeng.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingfeng.business.biz.session.ISessionCacheService;
import com.qingfeng.business.vo.session.CacheSessionObj;
import com.qingfeng.common.dto.ResultDTO;
import com.qingfeng.constant.FinalDatas;
import com.qingfeng.constant.enums.ErrorMessages;
import com.qingfeng.utils.StringTools;

public class SessionFilter implements Filter {
    private ApplicationContext app;
    private final static String VALIDATEPATHS     = "validatePaths";
    List<String>                validateList = new ArrayList<String>();
    private ServletContext      servletContext;
    private final static String QFWLSESSIONID = "QFWLSESSIONID";
    private final static String HEADER_AUTHORIZATIO="Authorization";
    ISessionCacheService sessionCacheService;
    public void destroy() {

    }
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException,
            ServletException {

        HttpServletRequest request = (HttpServletRequest) arg0;
        String uri = request.getServletPath();
         if (validatePath(uri)){//需要权限验证的地址
             String sessionId =null;
             String requeestsessionId =  request.getParameter(QFWLSESSIONID);
             Enumeration headersession = request.getHeaders(HEADER_AUTHORIZATIO);
             if(headersession!=null){
                 while(headersession.hasMoreElements()){
                     sessionId = (String)headersession.nextElement();
                 }
             }
             if(StringTools.isNullOrSpace(sessionId)){
                 Map<String, Object> map = new HashMap<String, Object>();
                 map.put("success", false);
                 map.put("errCode", ErrorMessages.NOT_AUTHORIZED.getErrCode());
                 map.put("info", ErrorMessages.NOT_AUTHORIZED.getErrInfo());
                 arg1.getWriter().print(JSON.toJSONString(map,SerializerFeature.DisableCircularReferenceDetect));
             }else{
                 /**
                  * 1、判断QFWLSESSIONID在缓存中是否存在
                  * 2、判断是否缓存中的数据是否包含用户对象
                  * 3、将信息放置到容器session中
                  */
                 ResultDTO<CacheSessionObj> rs = sessionCacheService.pullCacheSessionObj(sessionId);
                 if(rs.isSuccess()){
                     CacheSessionObj cacheObj = rs.getData();
                     if(cacheObj.getUserObj()==null){
                         Map<String, Object> map = new HashMap<String, Object>();
                         map.put("success", false);
                         map.put("errCode", ErrorMessages.NOT_AUTHORIZED.getErrCode());
                         map.put("info", ErrorMessages.NOT_AUTHORIZED.getErrInfo());
                         arg1.getWriter().print(JSON.toJSONString(map,SerializerFeature.DisableCircularReferenceDetect));
                     }else{
                         HttpSession session = request.getSession();
                         session.setAttribute(FinalDatas.USER_SESSION_KEY, cacheObj);
                         arg2.doFilter(arg0, arg1);
                     }
                 }else{
                     Map<String, Object> map = new HashMap<String, Object>();
                     map.put("success", false);
                     map.put("errCode", ErrorMessages.NOT_AUTHORIZED.getErrCode());
                     map.put("info", ErrorMessages.NOT_AUTHORIZED.getErrInfo());
                     arg1.getWriter().print(JSON.toJSONString(map,SerializerFeature.DisableCircularReferenceDetect));
                 }
             }
         }else{
             arg2.doFilter(arg0, arg1);
         }
        
    }

    public void init(FilterConfig cfg) throws ServletException {
        String validatePaths = cfg.getInitParameter(VALIDATEPATHS);
        String[] validateUri = validatePaths.split(",");
        validateList = Arrays.asList(validateUri);
        servletContext = cfg.getServletContext();
        app = getWebApplicationContext();
        sessionCacheService = app.getBean(ISessionCacheService.class);

    }

    private WebApplicationContext getWebApplicationContext() throws RuntimeException {
        Object ob = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        WebApplicationContext context = (WebApplicationContext) ob;
        return context;
    }

    protected Object getBean(String name) {
        return this.getWebApplicationContext().getBean(name);
    }
    
    private boolean validatePath(String path){
        boolean flag = false;
        if(StringTools.isNullOrSpace(path)){
            return flag;
        }
        for(String validatePath:validateList){
            if(path.contains(validatePath)){
                return true;
            };
        }
        return flag;
    }
}
